<template>
  <div v-loading="loading" class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="videoFormRef" label-width="120px" :model="form" :rules="rules"
               style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="课程类型" prop="courseType">
              <el-cascader v-model="form.courseType" :options="data.courseList" placeholder="请选择关联课程类型"
                           @change="changeCourseTypeHandle"
                           :props="{label:'name',value:'id',children:'children',emitPath:false}"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-select clearable v-model="form.type" placeholder="请选择类型">
                <el-option v-for="item in data.videoTypeList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="章节目录" prop="type">
              <el-select v-model="form.chapterCatalog" clearable placeholder="请选择章节目录">
                <el-option v-for="item in data.chapterList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="老师" prop="teacherId">
              <el-select clearable v-model="form.teacherId" placeholder="请选择老师">
                <el-option v-for="item in data.teacherList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="视频地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资料" prop="docId">
              <el-select clearable v-model="form.docId" placeholder="请选择资料">
                <el-option v-for="item in data.docList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="关联题库" prop="bankId">
              <el-select clearable v-model="form.bankId" placeholder="请选择题库">
                <el-option v-for="item in data.bankList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上传时间" prop="uploadTime">
              <el-date-picker
                  v-model="form.uploadTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="date"
                  placeholder="请选择上传时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="年份" prop="year">
              <el-date-picker
                  v-model="form.year"
                  value-format="YYYY"
                  type="year"
                  placeholder="请选择年份"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="排序" prop="orderNum">-->
          <!--              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="说明">
              <el-input v-model="form.remark" placeholder="请输入说明" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon class="el-input__icon input-icon" icon-class="back"/>
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon class="el-input__icon input-icon" icon-class="save"/>
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {addVideo, editVideo, getVideoDetail} from '@/api/resource/video'
import {listDictItemByCode} from '@/api/config/dic'
import {listTeacher} from '@/api/teacher'
import {listDoc} from '@/api/resource/doc'
import {listBank} from '@/api/resource/bank'

const {proxy} = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const loading = ref(false)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  videoTypeList: [],
  teacherList: [],
  docList: [],
  bankList: [],
  chapterList: []
})
const form = reactive({
  id: null,
  orderNum: '',
  name: '',
  courseType: '',
  type: '',
  teacherId: '',
  docId: '',
  bankId: '',
  uploadTime: '',
  year: '',
  publishedFlag: 1,
  url: '',
  remark: '',
  chapterCatalog: ''
})

const rules = ({
  // orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  name: [{required: true, message: '请输入名称', trigger: 'blur'}],
  courseType: [{required: true, message: '请选择课程类型', trigger: 'blur'}],
  type: [{required: true, message: '请选择类型', trigger: 'blur'}],
  teacherId: [{required: true, message: '请选择老师', trigger: 'blur'}],
  url: [{required: true, message: '请输入地址', trigger: 'blur'}],
  docId: [{required: true, message: '请选择资料', trigger: 'blur'}],
  uploadTime: [{required: true, message: '请选择上传时间', trigger: 'blur'}],
  year: [{required: true, message: '请选择年份', trigger: 'blur'}],
  publishedFlag: [{required: true, message: '请选择状态', trigger: 'blur'}],
})

// 详情
const initDetail = (row) => {
  getVideoDetail(row.id || route.query.id).then((res) => {
    Object.keys(form).forEach((key) => {
      form[`${key}`] = res.data[`${key}`]
    })
    form.courseType = res.data.courseType
    initDataCourseType()
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'videoTypeCode'}).then(res => {
    data.videoTypeList = res.rows
  })
  listDictItemByCode({typeCode: 'chapterCatalogCode'}).then(res => {
    data.chapterList = res.rows
  })
  listTeacher({}).then(res => {
    data.teacherList = res.rows
  })
  // listDoc({}).then(res => {
  //   data.docList = res.rows
  // })
  // listBank({}).then(res => {
  //   data.bankList = res.rows
  // })
}

const save = () => {
  proxy.$refs["videoFormRef"].validate(valid => {
    if (valid) {
      loading.value = true
      if (isAdd.value) {
        addVideo(form).then(res => {
          if (res.code === 200) {
            loading.value = false
            goBack()
            // tableItem.pageInfo.paging()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editVideo(form).then(res => {
          if (res.code === 200) {
            loading.value = false
            goBack()
            // tableItem.pageInfo.paging()
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}

function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

function changeCourseTypeHandle() {
  form.docId = ''
  form.bankId = ''
  initDataCourseType()
}

onMounted(() => {
  let titleMap = {
    add: '新增视频',
    edit: '修改视频',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  routeQuery.type == 'edit' ? '' : initDataCourseType()
  isAdd.value = routeQuery.type == 'add'
  initData()
})
const initDataCourseType = async () => {
  data.bankList = []
  let bankList = await listBank({courseType: form.courseType})
  data.bankList = bankList.rows
  data.docList = []
  let docList = await listDoc({courseType: form.courseType})
  data.docList = docList.rows
}
// watch(() => {
//   return form.courseType
// }, async () => {
//   console.log(form.courseType, 'form.courseType')
//   // 数据变化之后的回调函数

//   data.bankList = []
//   let bankList = await listBank({courseType: form.courseType})
//   data.bankList = bankList.rows
//   data.docList = []
//   let docList = await listDoc({courseType: form.courseType})
//   data.docList = docList.rows
// }, {immediate: true, deep: false})
</script>
